<?php
namespace  Mp\Service\Tree;

use Illuminate\Support\Fluent;
use Mp\Service\Tree\Node;
use BlueM\Tree as BTree;
use Illuminate\Contracts\Support\Renderable;

class Tree extends Fluent implements Renderable{

	protected $nodes;

	protected $label = 'tree';

	protected  $root ;

	protected $tree;

	protected $view = "Mp::tree.tree";



	protected function addNode(Node $node){
		$this->nodes = $this->nodes ?? collect();
		$this->nodes->push($node);
	}

	public function node($content){
		
		if($content instanceof Closure ){
			call_user_func($content , $this);
		}elseif(is_array($content)){
			$node = new Node($content);
			$this->addNode($node);
		}
		return $this;
	}

	public function nodes(Array $nodes){
		array_map(function($content){
			$this->node($content);
		},$nodes);
		return $this;	
	}

	private function _init(){

		$this->tree = new BTree($this->nodes->toArray(),['rootId'=> -1,'id'=>'node_id','parent'=>'parent_id']);
		$this->setRoot();

		$this->data = [
			'root' => reset($this->root),
			'label' => $this->label,
			'nodes' => $this->nodes,
		];	

	}

	public  function nodeRender(Node $node){
		
		return view('Mp::tree.node',[ 'node' => $this->tree->getNodeById($node->id) ]);
	}

	public function model($node){
		$id = $node->getId();
		return new Node(['id' => $id]);
	}


	private function setRoot(){
		$this->root = $this->tree->getRootNodes();
	}

	public function render(){
		$this->_init();
		$this->data = array_merge($this->data,$this->attributes);	
		return view($this->view,$this->data)->render();
	}

	public function __toString(){

		return $this->render();
	}


}